<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>购物车</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .container {
            max-width: 1200px;
            margin-left: 300px;
            padding: 20px;
            background: white;
            min-height: calc(100vh - 40px);
        }
        .cart-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid #eee;
        }
        .product-info { flex: 2; }
        .quantity-control {
            flex: 1;
            display: flex;
            align-items: center;
        }
        .quantity-control button {
            width: 30px;
            height: 30px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
        }
        .quantity-control span { margin: 0 10px; }
        .remove-btn {
            background: #ff5252;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
        }
        .checkout-section {
            margin-top: 20px;
            text-align: right;
        }
        #checkout-btn {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
    </style>
</head>
<body data-user-role="customer">
<!-- 引入增强版全局通知组件 -->
<div th:replace="~{common/enhanced-global-notification :: notification}"></div>

<div th:replace="~{common/customer-navbar :: navbar}"></div>

    <div class="container">
        <h1>我的购物车</h1>
        <div id="cart-items">
            <div th:each="cart : ${cartItems}">
                <div class="cart-item" th:each="bunch : ${cart.productBunches}" th:data-product-id="${bunch.productId}">
                    <div class="product-info">
                        <span th:text="${bunch.product.productName}">商品名称</span>
                        <span th:text="'¥'+${bunch.product.price}">价格</span>
                    </div>
                    <div class="quantity-control">
                        <button class="decrement">-</button>
                        <span th:text="${bunch.quantity}">数量</span>
                        <button class="increment">+</button>
                    </div>
                    <button class="remove-btn" th:data-bunch-id="${bunch.ProductBunchID}">删除</button>
                </div>
            </div>
        </div>

        <div class="checkout-section">
            <div class="address-select mb-3">
                <label for="address-select">选择收货地址：</label>
                <select id="address-select" class="form-control" required>
                    <option value="">请选择收货地址</option>
                </select>
                <div id="address-error" class="text-danger mt-1" style="display:none;"></div>
            </div>
            <p>总计: <span id="total-price">¥0.00</span></p>
            <button id="checkout-btn" class="btn btn-primary">结算</button>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // 加载用户地址
        loadUserAddresses();
        // 数量增减
        document.querySelectorAll('.increment').forEach(btn => {
            btn.addEventListener('click', function() {
                const cartItem = this.closest('.cart-item');
                const quantitySpan = this.previousElementSibling;
                const newQuantity = parseInt(quantitySpan.textContent) + 1;
                quantitySpan.textContent = newQuantity;
                updateCartItem(cartItem, newQuantity);
                updateTotal();
            });
        });

        document.querySelectorAll('.decrement').forEach(btn => {
            btn.addEventListener('click', function() {
                const cartItem = this.closest('.cart-item');
                const quantitySpan = this.nextElementSibling;
                const current = parseInt(quantitySpan.textContent);
                if (current > 1) {
                    const newQuantity = current - 1;
                    quantitySpan.textContent = newQuantity;
                    updateCartItem(cartItem, newQuantity);
                    updateTotal();
                }
            });
        });

        // 更新购物车项数量
        function updateCartItem(cartItem, newQuantity) {
            const bunchId = cartItem.querySelector('.remove-btn').getAttribute('data-bunch-id');
            fetch('/api/cart/update-quantity', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    bunchId: bunchId,
                    quantity: newQuantity
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('更新数量失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新数量失败，请刷新页面重试');
            });
        }

        // 删除商品
        document.querySelectorAll('.remove-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                if (!confirm('确定要删除这个商品吗？')) return;

                const bunchId = this.getAttribute('data-bunch-id');
                fetch('/api/cart/remove/' + bunchId, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (response.ok) {
                        this.closest('.cart-item').remove();
                        updateTotal();
                    } else {
                        throw new Error('删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除商品失败，请刷新页面重试');
                });
            });
        });

        // 加载用户地址
        function loadUserAddresses() {
            const userId = '[[${session.loggedInUser}]]';
            if (!userId || userId === '') return;

            fetch('/address/api/' + userId, {
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`获取地址失败，状态码: ${response.status}`);
                }
                return response.json();
            })
                .then(addresses => {
                    const select = document.getElementById('address-select');
                    select.innerHTML = '<option value="">请选择收货地址</option>';

                    if (!addresses || addresses.length === 0) {
                        select.innerHTML = '<option value="">暂无收货地址</option>';
                        select.disabled = true;
                        return;
                    }

                    addresses.forEach(address => {
                        const option = document.createElement('option');
                        option.value = address.addressId;
                        option.textContent = `${address.username} - ${address.address} (${address.phone})`;
                        select.appendChild(option);
                    });
                })
                .catch(error => {
                    console.error('加载地址失败:', error);
                    document.getElementById('address-error').textContent = '加载地址失败: ' + error.message;
                    document.getElementById('address-error').style.display = 'block';
                });
        }

        // 结算按钮
        document.getElementById('checkout-btn').addEventListener('click', function() {
            const btn = this;
            const addressSelect = document.getElementById('address-select');
            const addressError = document.getElementById('address-error');

            // 验证地址
            if (!addressSelect.value) {
                addressError.textContent = '请选择收货地址';
                addressError.style.display = 'block';
                return;
            }
            addressError.style.display = 'none';

            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';

            const cartItems = Array.from(document.querySelectorAll('.cart-item')).map(item => {
                return {
                    productId: item.dataset.productId,
                    quantity: parseInt(item.querySelector('.quantity-control span').textContent)
                };
            });

            const userId = '[[${session.loggedInUser}]]';
            console.log('当前用户ID:', userId);
            if (!userId || userId === '') {
                alert('用户未登录，请先登录');
                window.location.href = '/login';
                return;
            }

            console.log('准备发送结算请求，用户ID:', userId);
            console.log('购物车商品:', cartItems);

            // 获取并验证地址ID

            if (!addressSelect) {
                console.error('未找到地址选择元素');
                addressError.textContent = '系统错误：未找到地址选择控件';
                addressError.style.display = 'block';
                btn.disabled = false;
                btn.textContent = '结算';
                return;
            }

            const selectedOption = addressSelect.options[addressSelect.selectedIndex];
            if (!selectedOption || selectedOption.value === '') {
                console.error('未选择地址');
                addressError.textContent = '请选择有效的收货地址';
                addressError.style.display = 'block';
                btn.disabled = false;
                btn.textContent = '结算';
                return;
            }

            // 获取并验证地址ID
            const addressId = selectedOption.value;
            console.log('获取到的addressId:', addressId, '完整option:', selectedOption);

            // 调试输出选项数据
            try {
                const addressData = selectedOption.dataset.address ?
                    JSON.parse(selectedOption.dataset.address) : null;
                console.log('地址数据详情:', addressData);
            } catch (e) {
                console.error('解析地址数据失败:', e);
            }

            // 验证地址ID格式
            if (!addressId || addressId === 'undefined') {
                console.error('地址ID为空或undefined:', addressId);
                addressError.textContent = '地址ID无效，请重新选择';
                addressError.style.display = 'block';
                btn.disabled = false;
                btn.textContent = '结算';
                return;
            }

            // 检查是否为有效的UUID格式
            const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
            if (!uuidRegex.test(addressId)) {
                console.error('地址ID格式无效:', addressId);
                addressError.textContent = '地址ID格式不正确，请重新选择';
                addressError.style.display = 'block';
                btn.disabled = false;
                btn.textContent = '结算';
                return;
            }



            fetch('/api/orders/from-cart/' + userId, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    cartItems: cartItems,
                    addressId: addressId
                })
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message || '请求失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                if(data.success) {
                    // 显示成功提示
                    const successAlert = document.createElement('div');
                    successAlert.className = 'alert alert-success position-fixed top-0 start-50 translate-middle-x mt-3';
                    successAlert.style.zIndex = '9999';
                    successAlert.textContent = '订单创建成功，正在跳转...';
                    document.body.appendChild(successAlert);

                    // 2秒后跳转
                    setTimeout(() => {
                        window.location.href = '/customer/orders';
                    }, 2000);
                } else {
                    throw new Error(data.message || '结算失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                // 显示更详细的错误提示
                const errorAlert = document.createElement('div');
                errorAlert.className = 'alert alert-danger position-fixed top-0 start-50 translate-middle-x mt-3';
                errorAlert.style.zIndex = '9999';
                errorAlert.style.maxWidth = '80%';
                errorAlert.innerHTML = `
                    <div>结算失败</div>
                    <div style="font-size:0.8em;margin-top:5px;">${error.message || '未知错误'}</div>
                    <div style="font-size:0.8em;color:#666;">请检查网络连接或稍后再试</div>
                `;
                document.body.appendChild(errorAlert);

                // 5秒后自动消失
                setTimeout(() => {
                    errorAlert.remove();
                }, 5000);
            })
            .finally(() => {
                btn.disabled = false;
                btn.textContent = '结算';
            });
        });

        // 计算总价
        function updateTotal() {
            let total = 0;
            document.querySelectorAll('.cart-item').forEach(item => {
                const priceText = item.querySelector('.product-info span:nth-child(2)').textContent.replace('¥', '');
                const price = parseFloat(priceText);
                const quantity = parseInt(item.querySelector('.quantity-control span').textContent);
                total += price * quantity;
            });
            document.getElementById('total-price').textContent = '¥' + total.toFixed(2);
        }

        // 初始化总价
        updateTotal();
    });
    </script>
</body>
</html>
